#!/usr/bin/python
import socket, cards, sys, random

_HOST = 'localhost'
_PORT = 5555

class Client:
	def __init__(self, name): 
		self.sock = socket.socket()
		self.name = name
		self.hand = []
		self.moveMade = None
		self.connect()
		
	def connect(self):
		host = _HOST
		port = _PORT
		self.sock.connect((host, port))
		self.sock.send(self.name)
		resp = self.sock.recv(31)
		print resp
		while(True):
			self.hand = cards.Hand()
			self._playGame()
	
	def _getHand(self):
		return self.hand.getHandList(":")
		
	def _getRung(self):
		spades = clubs = diamonds = hearts = 0
		for i in range(0, self.hand.size()):
			card = self.hand.getCard(i)
			suite = card.suite
			if(suite == 'h'):
				hearts += 1
			elif(suite == 'd'):
				diamonds += 1
			elif(suite == 's'):
				spades += 1
			elif(suite == 'c'):
				clubs += 1
		highest = 0
		cSuite = None
		if(diamonds > highest):
			highest = diamonds
			cSuite = 'd'
		if(spades > highest):
			highest = spades
			cSuite = 's'
		if(clubs > highest):
			highest = clubs
			cSuite = 'c'
		if(hearts > highest):
			highest = hearts
			cSuite = 'h'
		return cSuite
		
	def _playGame(self):
		for i in range(0, 5):
			resp = self.sock.recv(2)
			self.hand.addCard(cards.str2Card(resp))
		
		self.hand.sortHand()
		print self.hand
		resp = self.sock.recv(21)
		if(resp[0] == "s"):
			print("enter the rung you want to choose(s for Spades, h for Hearts, d for Diamonds, c for Clubs): ");
			rung = self._getRung()
			self.sock.send(rung)
		else:
			print resp
		
		for i in range(0, 8):
			resp = self.sock.recv(2)
			self.hand.addCard(cards.str2Card(resp))
			
		self.hand.sortHand()
		print self.hand
		i = 0
		while(i < 13):
			j = 0
			msg = self.sock.recv(20)
			print "msg 1: " + msg
			while(j < 4):
				msg = self.sock.recv(32)
				if(msg[0] == "y"):
					#self.hand.printHand(True)
					print("")
					print(msg)
					card = self._getMove(self._getMoveColor(msg))
					print(card)
					self.sock.send(card.toString())
					i += 1
				else:
					print(msg)
				j += 1
		msg = self.sock.recv(32)
		print("game winner is team: " + msg)
		
	def _printHand(self):
		for i in range(0, self.hand.size()):
			print(str(i)+")"),
			self.hand.getCard(i).printCard()
		
	def _getMove(self, moveColor):
		if(moveColor == 'n'):
			ans = int(random.random()*self.hand.size())
			return self.hand.getCard(ans)			
		else:
			options = []
			for i in range(0, self.hand.size()):
				card = self.hand.getCard(i)
				if(card.suite == moveColor):
					options.append(card)
			bestMove = options[0]
			for option in options:
				if(option > bestMove):
					bestMove = option
			return bestMove
		
	def _getMoveColor(self, msg):
		rnd = msg.split(":")[1].split(";")
		if(rnd[0] != ''):
			print rnd
			moveColor = rnd[0][1]
			return moveColor
		else:
			return "n"

if(__name__ == '__main__'):
	if(len(sys.argv) < 2):
		print("usage: python client.py [username]")
	else:
		name = sys.argv[1]
		c = Client(name)
		#c.connect(_HOST, _PORT)
